import React, { useState ,useEffect } from 'react';
import { getSalaryApi,addSalaryApi,updateSalaryApi,delSalaryApi,searchSalaryApi ,updateCmisApi} from '@/api/wages/wages';
import { Table ,Input,Button,Modal,Form,Select,message,Popconfirm} from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import type { ColumnsType, TableProps } from 'antd/es/table';
import useStore from '@/store/index'
import { v4 as uuidv4 } from 'uuid';
import type { PaginationProps } from 'antd';
interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}
const { Search } = Input;
const { Option } = Select;
interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 16,
    },
  },
};



const Wages: React.FC = () => {
  
  const userInfo = useStore<any>((state: any) => state.userInfo)
  const [salaryList,setsalaryList] = useState<any>()
  const [pageNum,setPageNum] = useState(1)
  const [pageSize,setpageSize] = useState(5)
  const [total,setTotal] =useState(0)
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalTitle,setModalTitle] = useState<any>()
  const [form] = Form.useForm();

  

  useEffect(()=>{
    getSalary(pageNum,pageSize)
  },[])
  const columns: ColumnsType<DataType> = [
    {
      title: '姓名',
      width: 100,
      dataIndex: 'salaryName',
      key: '1',
      fixed: 'left',
    },
    {
        title: '部门',
        width: 100,
        dataIndex: 'department',
        fixed: 'left',
        key: '2',
      },
    {
      title: '年龄',
      width: 80,
      dataIndex: 'salaryAge',
      key: '3',
     
      sorter: true,
    },
    {
      title: '职位',
      width: 100,
      dataIndex: 'position',
      key: '4',
    },
    {
      title: '基本工资',
      width: 100,
      dataIndex: 'salary',
      key: '5',
    },
    {
      title: '商品提成',
      width: 100,
      dataIndex: 'goodsCmis',
      key: '7',
    },
    {
        title: '套餐提成',
        width: 100,
        dataIndex: 'packageCmis',
        key: '8',
    },
    {
        title: '消费提成',
        width: 100,
        dataIndex: 'baseCmis',
        key: '9',
    },
    {
        title: '全勤奖',
        width: 100,
        dataIndex: 'fullDay',
        key: '10',
    },
    {
        title: '餐补',
        width: 100,
        dataIndex: 'foodPerk',
        key: '11',
    },
    {
        title: '签到天数',
        width: 100,
        dataIndex: 'workDay',
        key: '12',
    },
    {
        title: '请假天数',
        width: 100,
        dataIndex: 'notWorkDay',
        key: '13',
    },
    {
        title: '当前月份',
        width: 100,
        dataIndex: 'month',
        key: '14',
    },
    {
        title: '应发工资',
        width: 100,
        dataIndex: 'totalSalary',
        key: '15',
    },
    
    {
      title: '操作',
      key: '16',
      fixed: 'right',
      width: 280,
      render: (record) => <div>
        <Button type="primary" style={{marginRight:'10px'}} onClick={()=>showModal('修改提成',record)} >修改提成</Button>
        <Button type="primary" style={{marginRight:'10px'}} onClick={()=>showModal('修改基本信息',record)} >修改</Button>
        
        <Popconfirm
          title="删除员工"
          description="删除后无法恢复!确认永久删除?"
          onConfirm={()=>confirm(record)}
          onCancel={()=>cancel(record)}
          okText="Yes"
          cancelText="No"
        >
          <Button type='primary'  danger>删除</Button>
        </Popconfirm>
      </div>,
    },
  ];
  
  // 获取员工函数
  const getSalary = async (pageNum:any,pageSize:any)=>{
    let getSalaryParams = {pageNum:pageNum,pageSize:pageSize,belongToShop:1,isDel:0}
    try {
      let getSalaryRes =  await getSalaryApi(getSalaryParams)
      if(getSalaryRes.code == 200){
      let newSalary =  getSalaryRes.salaryData.map((salary:any)=>{
          return{
            id:salary.id,
            key:salary.id,
            salaryName:salary.salaryName,
            salaryAge:salary.salaryAge,
            department:salary.department,
            position:salary.position,
            salary:salary.salary,
            goodsCmis:salary.goodsCmis,
            packageCmis:salary.packageCmis,
            baseCmis:salary.baseCmis,
            fullDay:salary.fullDay,
            foodPerk:salary.foodPerk,
            workDay:salary.workDay,
            notWorkDay:salary.notWorkDay,
            month:salary.month,
            createTime:salary.createTime,
            totalSalary:salary.totalSalary,
            belongToShop:salary.belongToShop,
          }
        })
        setsalaryList(newSalary)
        setTotal(getSalaryRes.total)
      }
    } catch (error) {
      
    }
  }
  // 模态框
  const showModal = (val:string,record:any) => {
    if(record){
      form.setFieldsValue(record)
    }else{
      form.setFieldsValue({id:uuidv4(),belongToShop:userInfo.storeId})
    }
    setModalTitle(val)
    setIsModalOpen(true);
  };
  // 模态框关闭函数
  const handleOk = () => {
    form.resetFields()
    setIsModalOpen(false);
  };
  // 模态框取消
  const handleCancel = () => {
    form.resetFields()
    setIsModalOpen(false);
  };
  const onFinish = async (values: any) => {
    values.belongToShop = userInfo.storeId + ''
    let addParams = values
    if(modalTitle == '添加工资单'){
      try {
        let addSalaryRes =  await addSalaryApi(addParams)
        if(addSalaryRes.code == 200){
          message.open({
            type:"success",
            content:addSalaryRes.msg
          })
          // 关闭弹窗
          handleOk()
          // 重新获取用户
          getSalary(pageNum,pageSize)
        }else{
          message.open({
            type:"error",
            content:addSalaryRes.msg
          })
        }
      } catch (error) {
        message.open({
            type:"error",
            content: '添加失败'+ error
          })
      }
    }else if(modalTitle == '修改提成'){
      try {
        let updateCmisRes =  await updateCmisApi(addParams)
        if(updateCmisRes.code == 200){
          message.open({
            type:"success",
            content:updateCmisRes.msg
          })
          // 关闭弹窗
          handleOk()
          // 重新获取用户
          getSalary(pageNum,pageSize)
        }else{
          message.open({
            type:"error",
            content:updateCmisRes.msg
          })
        }
      } catch (error) {
        message.open({
            type:"error",
            content: '修改失败'+ error
          })
      }
    }else if(modalTitle == '修改基本信息'){
      try {
        let updateSalaryRes =  await updateSalaryApi(addParams)
        if(updateSalaryRes.code == 200){
          message.open({
            type:"success",
            content:updateSalaryRes.msg
          })
          // 关闭弹窗
          handleOk()
          // 重新获取用户
          getSalary(pageNum,pageSize)
        }else{
          message.open({
            type:"error",
            content:updateSalaryRes.msg
          })
        }
      } catch (error) {
        message.open({
            type:"error",
            content: '修改失败'+ error
          })
      }
    }
  };
  // 页码改变触发
  const pageNumChange: PaginationProps['onChange'] = (page) => {
    setPageNum(page);
    getSalary(page, pageSize)
  };
  const fresh = ()=>{
    try {
        getSalary(pageNum,pageSize)
      message.open({
        type:'success',
        content:"刷新成功"
      })
    } catch (error) {
      message.open({
        type:'error',
        content:"刷新失败"
      })
    }
  }
  // 气泡删除确认框
  const confirm = async (e: any) => {
    let delStaffParams = {id:e.id}
     try {
      let delStaffRes = await delSalaryApi(delStaffParams)
      if(delStaffRes.code == 200){
        message.success('删除员工成功');
        getSalary(pageNum,pageSize)
      }else{
        message.error('删除员工失败' + delStaffRes.msg);
      }
     } catch (error) {
      message.error('删除员工失败' + error);
     }
  };
  
  const cancel = (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
    message.success('取消成功');
  };
  const onSearch: any =  async(value: string) => {
    if(value){
    let searchParams = {keyWord:value,belongToShop:userInfo.storeId}
    try {
      let searchRes = await searchSalaryApi(searchParams)
      if(searchRes.code ==200){
        let newsalaryList = searchRes.salary.map((salary:any)=>{
          return {
            id:salary.id,
            key:salary.id,
            salaryName:salary.salaryName,
            salaryAge:salary.salaryAge,
            department:salary.department,
            position:salary.position,
            salary:salary.salary,
            goodsCmis:salary.goodsCmis,
            packageCmis:salary.packageCmis,
            baseCmis:salary.baseCmis,
            fullDay:salary.fullDay,
            foodPerk:salary.foodPerk,
            workDay:salary.workDay,
            notWorkDay:salary.notWorkDay,
            month:salary.month,
            createTime:salary.createTime,
            totalSalary:salary.totalSalary,
            belongToShop:salary.belongToShop,
          }
        })
        setsalaryList(newsalaryList)
        message.success(searchRes.msg)
      }else {
        message.error(searchRes.msg)
      }
    } catch (error) {
      message.error('搜索失败'+error)
    }
    }
  }
    return (
       <div>
         <div>
          <Search
              placeholder="姓名/部门"
              allowClear
              enterButton="搜索"
            // style={{ width: 304 }}
              onSearch={onSearch}
              style={{ width: 300 }}
              />
             <Button style={{marginRight: '10px', marginLeft: '10px'}} onClick={()=>showModal('添加工资单',null)} className='vip_btn' type="primary" >
              添加工资单
            </Button>
            
            <Button style={{marginRight: '10px', marginLeft: '10px'}} onClick={fresh} className='vip_btn' type="primary" shape="circle" icon={<ReloadOutlined />} />
          </div>
          <Table columns={columns} dataSource={salaryList} scroll={{ x: 1500, y: 600 }} 
           pagination={{
            pageSize: pageSize,
            defaultCurrent: pageNum,
            total: total,
            onChange: pageNumChange,
          }}/>
          <Modal footer={null} title={modalTitle} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
         >
          <Form
            form={form}
            name="register"
            onFinish={onFinish}
            initialValues={{ residence: ['zhejiang', 'hangzhou', 'xihu'], prefix: '86' }}
            style={{ maxWidth: 600 }}
            scrollToFirstError
          >
            <Form.Item
              name="id"
              label="编号"
              rules={[{ required: true, message: '编号是必传参数', whitespace: true }]}
            >
              <Input disabled={true} />
            </Form.Item>
            <Form.Item
              name="salaryName"
              label="姓名"
              rules={[{ required: true, message: '姓名是必传参数', whitespace: true }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="salaryAge"
              label="年龄"
              rules={[{ required: true, message: '年龄性别是必传参数', whitespace: true }]}
              hidden={modalTitle == '修改提成' ? true :false}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="department"
              label="部门"
              rules={[{ required: true, message: '部门是必传参数', whitespace: true }]}
              hidden={modalTitle == '修改提成' ? true :false}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="position"
              label="职位"
              rules={[{ required: true, message: '职位是必传参数' }]}
              hidden={modalTitle == '修改提成' ? true :false}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="salary"
              label="基本工资"
              rules={[{ required: true, message: '基本工资是必传参数', whitespace: true }]}
              hidden={modalTitle == '修改提成' ? true :false}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="foodPerk"
              label="餐补"
              rules={[{ required: true, message: '餐补是必传参数', whitespace: true }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="goodsCmis"
              label="商品提成"
              rules={modalTitle == '修改提成' ? [{ required: true, message: '商品提成是必传参数', whitespace: true }] :[] }
              hidden={modalTitle !== '修改提成' ? true : false}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="packageCmis"
              label="套餐提成"
              rules={modalTitle == '修改提成' ? [{ required: true, message: '商品提成是必传参数', whitespace: true }] :[] }
              hidden={modalTitle !== '修改提成' ? true : false}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="baseCmis"
              label="消费提成"
              rules={modalTitle == '修改提成' ? [{ required: true, message: '商品提成是必传参数', whitespace: true }] :[] }
              hidden={modalTitle !== '修改提成' ? true : false}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="fullDay"
              label="全勤奖"
              rules={modalTitle == '修改提成' ? [{ required: true, message: '商品提成是必传参数', whitespace: true }] :[] }
              hidden={modalTitle !== '修改提成' ? true : false}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="workDay"
              label="签到天数"
              rules={modalTitle == '添加工资单' && modalTitle !== '修改提成' ?  []:[{ required: true, message: '签到天数是必传参数', whitespace: true }]}
              hidden={modalTitle == '添加工资单' ? true : false}
            >
              <Input disabled={modalTitle == '添加工资单' ? true : false} />
            </Form.Item>
            <Form.Item
              name="notWorkDay"
              label="请假天数"
              rules={modalTitle == '添加工资单' && modalTitle !== '修改提成' ?  [] :[{ required: true, message: '请假天数是必传参数', whitespace: true }]}
              hidden={modalTitle == '添加工资单' ? true : false}
            >
              <Input  />
            </Form.Item>
            
            <Form.Item {...tailFormItemLayout}>
              <Button onClick={handleOk} style={{ marginRight: 20 }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {modalTitle == '添加工资单' ? '添加' :'修改'}
              </Button>
            </Form.Item>
          </Form>
          </Modal>
       </div>
    )
}

export default Wages;
